'''图片格式转换类.
把目标文件夹inDir的图片转换并输出到outDir,outRate表示大小比例,可指定最小长度.方法main()执行转换'''

import sys
import os
import time

from PIL import Image

class picExchanger:

    def __init__(self,inDir='',outDir='',outRate=0.75,minLength=900):
        self.inDir=inDir
        self.outDir=outDir
        self.outRate=outRate
        self.minLength=minLength
        return

    def exchangeAPic(self,inPic,outPic):
        try:
            imIn=Image.open(inPic)
            if(imIn.size[0]>self.minLength and self.outRate<1):
                imIn.thumbnail((int(imIn.size[0]*self.outRate),int(imIn.size[0]*self.outRate)))
            imIn.save(outPic)
            imIn.close()
            return True
        except:
            return False

    def main(self):
        try:
            os.mkdir(self.outDir)
            print('%s folder has been created!' % self.outDir)
        except:
            print('%s folder could not be created!' % self.outDir)
            temp = input('input 1 enter to exit,0 enter to continue')
            if (temp == '1'):
                return
        totallyChange=0
        for fn in os.listdir(self.inDir):
            if(self.exchangeAPic(self.inDir+'\\'+fn,self.outDir+'\\'+fn.split(r'.')[0]+r'.jpg')):
                totallyChange+=1
                if(totallyChange%200==0):
                    print('已转换 '+str(totallyChange)+' 个文件')
        print('Totally exChange '+str(totallyChange)+' files!')
        return

if __name__=='__main__':
    inDir=r'F:\CG\PC官方\[でぼの巣製作所] 神楽黎明記 ～小春の章～'
    outDir=r'F:\CG\PC官方\[でぼの巣製作所] 神楽黎明記 ～小春の章～(jpg_exchange)'
    pe=picExchanger(inDir,outDir,1)
    pe.main()